<?php

/**
 * categories actions.
 *
 * @package    master_directory
 * @subpackage categories
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class categoriesActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
  	$this->form = new CategoryForm();
  	
   // $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategories();
   
   // $this->master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
   
  	$this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id")));
    
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($this->directory->getId());
    
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->category = Doctrine_Core::getTable('Category')->find(array($request->getParameter('id')));
    $this->forward404Unless($this->category);
    
    $this->form = new CategoryForm($this->category);
    
  //  $this->master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
	
    $this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id")));
        
    return $this->renderPartial('category',array('form'=>$this->form, 'directory' => $this->directory));    
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new CategoryForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $form = new CategoryForm();

    $this->processForm($request, $form);
    
    $category_id = $form->getObject()->getId();
    
    $directory_id = $form->getObject()->getMasterDirectoryId();

    //$this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategories();
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    
//    $this->master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
    
    $category = new Category();
  	$category->setMasterDirectoryId($directory_id);
  	
  	$this->form = new CategoryForm($category);
  	
  	$action_str = "Category created ID: " . $category_id;
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));
  	
  	$this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id")));
    
    return $this->renderPartial('category_container',array('categories' => $this->categories, 'directory' => $this->directory, 'form' => $this->form));    
    
    
  }

  public function executeEdit(sfWebRequest $request)
  {
  
    $this->forward404Unless($category = Doctrine_Core::getTable('Category')->find(array($request->getParameter('id'))), sprintf('Object category does not exist (%s).', $request->getParameter('id')));
    $this->form = new CategoryForm($category);
  }

  public function executeUpdate(sfWebRequest $request)
  {
  	
  	
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($category = Doctrine_Core::getTable('Category')->find(array($request->getParameter('id'))), sprintf('Object master_directory does not exist (%s).', $request->getParameter('id')));
    $form = new CategoryForm($category);
    
    $previous_name = $category->getName();

    $this->processForm($request, $form);
    
    $new_name = $category->getName();
    
    if($previous_name != $new_name){
    	
    	$levels = $category->getLevel();
    	
    	foreach ($levels as $level) {
    		
	    	$templates = array();
	  		$template2levels = $level->getTemplate2Level();
	  		$upper_levels = $level->getUpperLevel();
	  		$side_levels = $level->getSideLevel();
	  		
	  		foreach ($template2levels as $template2level) {
	  			array_push($templates, $template2level->getTemplate());
	  			
	  			$t2l_name_arr = explode(".", $template2level->getName());
	  			$template2level->setName($new_name . "." .$t2l_name_arr[1]);
	  			//$template2level->setName(str_replace($previous_name, $new_name, $template2level->getName()));
	  			$template2level->save();
	  			
	  			
	  		$generated_uppers = $template2level->getUpperLevel();
  			foreach ($generated_uppers as $generated_upper) {
  				$upper_name_arr = explode(".", $generated_upper->getName());
  				$upper_name_arr[0] = $new_name;
  				$upper_name_replaced = "";
  				foreach ($upper_name_arr as $upper_name) {
  					$upper_name_replaced .= $upper_name . ".";
  				}
  				$upper_name_replaced = substr($upper_name_replaced, 0, strlen($upper_name_replaced) - 1);
  				//$generated_upper->setName(str_replace($previous_name, $new_name, $generated_upper->getName()));
  				$generated_upper->setName($upper_name_replaced);
  				$generated_upper->save();
  			}
  			
  			$generated_sides = $template2level->getSideLevel();
  			foreach ($generated_sides as $generated_side) {
  				
  				$side_name_arr = explode(".", $generated_side->getName());
  				$side_name_arr[0] = $new_name;
  				$side_name_replaced = "";
  				foreach ($side_name_arr as $side_name) {
  					$side_name_replaced .= $side_name . ".";
  				}
  				$side_name_replaced = substr($side_name_replaced, 0, strlen($side_name_replaced) - 1);
  				
  				//$generated_side->setName(str_replace($previous_name, $new_name, $generated_side->getName()));
  				$generated_side->setName($side_name_replaced);
  				$generated_side->save();
  			}
	  			
	  			/*$generated_uppers = $template2level->getUpperLevel();
	  			foreach ($generated_uppers as $generated_upper) {
	  				$generated_upper->setName(str_replace($previous_name, $new_name, $generated_upper->getName()));
	  				$generated_upper->save();
	  			}
	  			
	  			$generated_sides = $template2level->getSideLevel();
	  			foreach ($generated_sides as $generated_side) {
	  				$generated_side->setName(str_replace($previous_name, $new_name, $generated_side->getName()));
	  				$generated_side->save();
	  			}*/
	  			
	  		}
	  		foreach ($upper_levels as $upper_level) {
	  			array_push($templates, $upper_level->getTemplate2Level()->getTemplate());
	  			
	  			$upper_name_arr = explode(".", $upper_level->getName());
  				$upper_name_arr[0] = $new_name;
  				$upper_name_replaced = "";
  				foreach ($upper_name_arr as $upper_name) {
  					$upper_name_replaced .= $upper_name . ".";
  				}
  				$upper_name_replaced = substr($upper_name_replaced, 0, strlen($upper_name_replaced) - 1);
  				//$generated_upper->setName(str_replace($previous_name, $new_name, $generated_upper->getName()));
  				$upper_level->setName($upper_name_replaced);
	  			
	  			/*$upper_level->setName(str_replace($previous_name, $new_name, $upper_level->getName()));
	  			$upper_level->save();*/
	  		}
	  		foreach ($side_levels as $side_level) {
	  			array_push($templates, $side_level->getTemplate2Level()->getTemplate());
	  			
	  			$side_name_arr = explode(".", $side_level->getName());
  				$side_name_arr[0] = $new_name;
  				$side_name_replaced = "";
  				foreach ($side_name_arr as $side_name) {
  					$side_name_replaced .= $side_name . ".";
  				}
  				$side_name_replaced = substr($side_name_replaced, 0, strlen($side_name_replaced) - 1);
  				
  				$side_level->setName($side_name_replaced);
  				$side_level->save();
	  			
	  			/*$side_level->setName(str_replace($previous_name, $new_name, $side_level->getName()));
	  			$side_level->save();*/
	  		}
	  		
	  		foreach ($templates as $template) {
	  			$contents = $template->getTemplateContent();
	  			foreach ($contents as $content) {
	  				$content_str = $content->getTheContent();
	  				
		  			$matchPattern = "/#%#(.*?)#%#/";
				
					$variables_str = array();
					$variables_names = array();
					//TODO: sustituir el nombre de la categoria modificada
					if (preg_match_all ( $matchPattern, $content_str, $matches )) {
						$variables_str = $matches[0];
						$variables_names = $matches[1];
						$variables_names = array_unique($variables_names);
						
						//foreach ($variables_str as $variable_str) {
						foreach ($variables_names as $variable_name) {
							$variable_name_arr = explode(".", $variable_name);
							if($variable_name_arr[0] ==  $previous_name){
							//echo $variable_arr[0] . " - " . "#%#" . $new_name . "<br>";
							
							$name_replaced = $new_name . ".";
			  				for ($index = 1; $index < count($variable_name_arr); $index++) {
			  					$name_replaced .= $variable_name_arr[$index] . ".";
			  				}
			  				
			  				$name_replaced = substr($name_replaced, 0, strlen($name_replaced) - 1);
			  				
			  				$content->setTheContent(str_replace("#%#".$variable_name."#%#", "#%#".$name_replaced."#%#", $content->getTheContent()));
							}
								
							/*if($variable_arr[0] != "#%#" . $new_name){
								$variable_str_replaced = str_replace($previous_name, $new_name, $variable_str);
								//echo $variable_str . " - " . $variable_str_replaced. "<br>";
				  				$content->setTheContent(str_replace($variable_str, $variable_str_replaced, $content->getTheContent()));
							}*/
						}
		  				$content->save();
					}
	  			}
	  		}
    		
    		
    	}
     	
    }
    
    $category_id = $category->getId();
    
    $directory_id = $form->getObject()->getMasterDirectoryId();
    
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    
   // $this->master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
    
    $category = new Category();
  	$category->setMasterDirectoryId($directory_id);
  	
  	$this->form = new CategoryForm($category);
  	
  	$action_str = "Category updated ID: " . $category_id;
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));
  	
  	$this->directory = Doctrine_Core::getTable('MasterDirectory')->find(array($this->getUser()->getAttribute("directory_id")));
    
    return $this->renderPartial('category_container',array('categories'=>$this->categories, 'directory' => $this->directory, 'form' => $this->form));  	
  	
  }
  
  public function executeLoadCategoryData(sfWebRequest $request){
  	
  	$directory_id = $request->getParameter('directory_id');
  	
  	$category = new Category();
  	$category->setMasterDirectoryId($directory_id);
  	
  	$this->form = new CategoryForm($category);
  	
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    
    $this->master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();  	
    
    $this->selected_directory = $directory_id;
    
    //return $this->renderPartial('category_container',array('categories'=>$this->categories, 'master_directories' => $this->master_directories, 'form' => $this->form));
    return $this->renderPartial('table',array('categories'=>$this->categories));
  }
  

  public function executeDelete(sfWebRequest $request)
  {
  	$this->forward404Unless($category = Doctrine_Core::getTable('Category')->find(array($request->getParameter('id'))), sprintf('Object master_directory does not exist (%s).', $request->getParameter('id')));
  	
  	$action_str = "Category deleted ID: " . $category->getId();
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));
  	$directory = $category->getMasterDirectory();
  	//levels
  	$levels = $category->getLevel();
  	foreach ($levels as $level) {
  		//echo 'level id:' . $level->getId() .' <br>';
  		
  		//templates
  		$templates = array();
  		$template2levels = $level->getTemplate2Level();
  		$upper_levels = $level->getUpperLevel();
  		$side_levels = $level->getSideLevel();
  		
  		foreach ($template2levels as $template2level) {
  			array_push($templates, $template2level->getTemplate());
  		}
  		foreach ($upper_levels as $upper_level) {
  			array_push($templates, $upper_level->getTemplate2Level()->getTemplate());
  		}
  		foreach ($side_levels as $side_level) {
  			array_push($templates, $side_level->getTemplate2Level()->getTemplate());
  		}
  		
  		$templates = array_unique($templates);
  			
  		foreach ($templates as $template) {
  			
  			//echo 'tplt id:' . $template->getId() .' <br>';
  			
  			$remainingTemplate2levels = $template->getTemplate2Level();
  			foreach ($remainingTemplate2levels as $remainingTemplate2level) {
	  			$sideLevels = $remainingTemplate2level->getSideLevel();
	  			foreach ($sideLevels as $sideLevel) {
	  				$sideLevel->delete();
	  			}
	  			$upperLevels = $remainingTemplate2level->getUpperLevel();
	  			foreach ($upperLevels as $upperLevel) {
	  				//echo 'deleting upper <br>';
	  				$upperLevel->delete();
	  			}
	  			
	  			$remainingTemplate2level->delete();
  			}
  			
  			if($template->getId() == $directory->getHomeTemplateId()){
  				$directory->setHomeTemplateId(null);
  				$directory->save();
  			}
  			$directory_search = Doctrine_Core::getTable('SearchConfiguration')->getByDirectory($directory->getId());
  			foreach ($directory_search as $search) {
  				if($search->getTemplateId() == $template->getId()){
	  				$search->delete();
  				}
  			}
  			
  			$template_contents = $template->getTemplateContent();
  			foreach ($template_contents as $template_content) {
  				$template_content->delete();
  			}
  			$templates_with_footer = Doctrine_Core::getTable('Template')->getTemplatesWithTemplateFooter($template->getId());
  			foreach ($templates_with_footer as $template_with_footer) {
  				$template_with_footer->setFooterId(null);
  				$template_with_footer->save();
  			}
  			$template->delete();
  		}
  		
  		//listings
  		$listings = array();
  		$listing2levels = $level->getListing2level();
  		foreach ($listing2levels as $listing2level) {
  			array_push($listings, $listing2level->getListing());
  			$listing2level->delete();
  		}
  		$listings = array_unique($listings);
  		foreach ($listings as $listing) {
  			$fields = $listing->getListFields();
  			foreach ($fields as $field) {
  				$selections = $field->getListingSelection();
  				foreach ($selections as $selection) {
  					$selection2contents = $selection->getListingSelection2categoryContent();
  					foreach ($selection2contents as $selection2content) {
  						$selection2content->delete();
  					}
  					$selection->delete();
  				}
	  			$field->delete();
  			}
  			$listing->delete();
  		}
  	}
  	foreach ($levels as $level) {
  		$level->delete();
  	}
  	
  	//get category contents
  	$contents = Doctrine_Core::getTable('CategoryContent')->getCategoryContentByCategoryId($category->getId());
  	foreach ($contents as $content) {
  		$content->delete();
  	}
  	
    $directory_id = $category->getMasterDirectoryId();
  	
    $category->delete();
    
    $this->getUser()->setFlash('save', 'deleted', false);
    
   // $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategories();
    
    $this->categories = Doctrine_Core::getTable('Category')->retreiveActiveCategoriesByDirectory($directory_id);
    
    //$this->master_directories = Doctrine_Core::getTable('MasterDirectory')->retreiveActiveDirectories();
    
    $this->form = new CategoryForm();
    
    /*$action_str = "Category deleted ID: " . $category->getId();
  	DirectoryUtils::registerTrace($action_str, $this->getUser()->getAttribute("user_id"));*/
  	
  	$this->directory = $directory;
    
    return $this->renderPartial('category_container',array('categories'=>$this->categories, 'directory' => $this->directory, 'form' => $this->form));
  	
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
  	
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    
    if ($form->isValid())
    {
    	
      $category = $form->save();
       $this->getUser()->setFlash('save', 'saved', false);

     // $this->redirect('categories/edit?id='.$category->getId());
    }else {
    }

  }
 
}
